/* test for ChatServer.cpp word thread */

#include "ChatMsg.hpp"

#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

using namespace std;

int main()
{   
    /* 1.创建侦听套接字
     * 2.发起连接
     * */
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        perror("socket");
        return 0;
    }
    
    struct sockaddr_in ser_addr;
    ser_addr.sin_family = AF_INET;
    ser_addr.sin_port = htons(28989);
    ser_addr.sin_addr.s_addr = inet_addr("101.43.7.28");    //服务端的IP
    
    int ret = connect(sockfd, (struct sockaddr*)&ser_addr, sizeof(ser_addr)) ;
    if(ret < 0)
    {
        perror("connect");
        return 0;
    }


    /* 循环处理
     * 3.发收数据
     * */
    while(1)
    {
        ChatMsg chat_msg;
        
        string s1, s2, s3, s4;
        int s_type;
        printf("please enter msg-type{1#Register, 2#Login, 3#AddFriend, 4#SendMsg, 5#PushMsg, 6#PushAddFriendMsg, 7#GetFriendMsg}:");
        fflush(stdout);
        cin >> s_type;
        switch(s_type)
        {
            case 1:
                cin >> s1 >> s2 >> s3 >> s4;
                chat_msg._msg_type = Register;
                chat_msg.SetValue("nickname", s1);
                chat_msg.SetValue("school", s2);
                chat_msg.SetValue("telnum", s3);
                chat_msg.SetValue("passwd", s4);
                break;
            
            case 2:
                cin >> s1 >> s2;
                chat_msg._msg_type = Login;
                chat_msg.SetValue("telnum", s1);
                chat_msg.SetValue("passwd", s2);
                break;

            case 3:
                cin >> s1 >> s2;  //user1, user2 的telnum
                chat_msg._msg_type = AddFriend;
                chat_msg._user_id = atoi(s1.c_str());
                chat_msg.SetValue("telnum", s2);
                break;
                
        }


        string msg;
        chat_msg.GetStringMsg(&msg);

        ssize_t send_size = send(sockfd, msg.c_str(), msg.size(), 0);    //发数据
        if(send_size < 0)
        {
            perror("send");
            continue;
        }
       
#if 1
        char buf[1024] = {0};
        memset(buf, '\0', sizeof(buf));
        ssize_t recv_size = recv(sockfd, buf, sizeof(buf), 0);    //收数据
        if(recv_size < 0)
        {
            continue;
        }
        else if(recv_size == 0)
        {
            printf("server shutdown !\n");
            close(sockfd);
            break;
        }

        msg.clear();
        msg.assign(buf, strlen(buf));
        chat_msg.Clear();
        chat_msg.GetChatMsg(-1, msg);
        if(chat_msg._user_id < 0)
        {
            cout << "filed" << endl;
        }
        else{
            cout << "success" << endl;
        }


        cout << "Get form Server:" << endl;
        cout << buf << endl;
#endif
    }

    close(sockfd);
    return 0;
}
